package fun.coding.leetcode;

public class ReverseInteger {
    
    public static void main(String[] args) {
    	int a = Integer.MAX_VALUE;
    	System.out.println("a is " + a);
    	// Just like two's complement, it will turn negative -1*2^31
    	int b = a + 1;
    	System.out.println("b is " + b);
    	
    	System.out.println("-1/10 is " + -1/10 + ", -1%10 is " + -1%10);
    	System.out.println("-14/10 is " + -14/10 + ", -14%10 is " + -14%10);
    	
    	// Test case begin
        ReverseInteger ins = new ReverseInteger();
        
        System.out.println(ins.reverse(1534236469));
    }
    /**
     *  Example1: x = 123, return 321
    	Example2: x = -123, return -321
    
	    Have you thought about this?
	    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
	    
	    Note: when reverse, think about leading 0s
	    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
	    
	    Note: when reverse, think about 
	    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
	    
	    Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function 
	    (ie, add an extra parameter).
	    Or use string as return values.  
     */
    public int reverse(int x) {
        int sign = (x > 0) ? 1 : -1;
        
        if(sign == -1) {
            x = x * -1;
        }
        
        int ret = 0;
        while (x > 0) {
            int digit = x % 10;
            if (ret > (Integer.MAX_VALUE - digit) / 10) {
            	return 0;
            }
            ret = ret * 10 + digit;
            x = x / 10;
        }
        
        return ret * sign;
    }
    
    
    /**
     *  This simplifies the code a lot. -1 / 10 = 0. -14 % 10 = -4;
     *  Also, could use long to represent the result
     */
    public int reverseNew(int x) {
        long ret = 0, digit = 0;
        
        while (x != 0) {
            digit = x % 10;
            ret = ret * 10 + digit;
            x = x / 10;
        }
        
        if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) return 0;
        
        return (int)ret;
    }
    
}
